package com.heima.consumer;

import com.heima.entity.OrderInfo;
import com.heima.entity.SeckillGoods;
import com.heima.entity.SeckillMessage;
import com.heima.entity.SeckillOrder;
import com.heima.mapper.SeckillGoodsMapper;
import com.heima.mapper.SeckillOrderMapper;
import com.heima.service.OrderService;
import com.heima.vo.GoodsVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Component
public class SeckillConsumer {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    
    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;
    
    @RabbitListener(queues = "seckill.queue")
    @Transactional
    public void handleSeckillMessage(SeckillMessage message) {
        Long userId = message.getUserId();
        Long goodsId = message.getGoodsId();
        
        try{
            // 1. 检查数据库库存
            SeckillGoods goods = seckillGoodsMapper.getSeckillGoodsByGoodsId(goodsId);
            if (goods == null || goods.getStockCount() <= 0) {
                return;
            }

            // 2. 检查用户是否已购买
            SeckillOrder order = seckillOrderMapper.selectByUserIdAndGoodsId(userId, goodsId);
            if (order != null) {
                return;
            }

            // 3. 数据库扣减库存
            int result = seckillGoodsMapper.reduceStock(goodsId);
            if (result <= 0) {
                return;
            }


            // 4. 创建订单
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(goods, goodsVo);
            OrderInfo orderInfo = orderService.createOrder(userId, goodsVo);

            // 2. 同步到Redis：将用户加入“已购买集合”
            String boughtKey = "seckill:bought:" + goodsId;
            redisTemplate.opsForSet().add(boughtKey, userId);
            // 设置过期时间（与秒杀活动周期一致，如24小时）
            redisTemplate.expire(boughtKey, 24, TimeUnit.HOURS);

            // 订单创建成功后，更新用户状态为“成功”
            redisTemplate.opsForValue().set(
                    "seckill:user:queue:" + userId + ":" + goodsId,
                    "success:" + orderInfo.getId(),  // 携带订单号
                    86400,  // 保留1天，方便查询
                    TimeUnit.SECONDS
            );
        }catch (Exception e) {
            // 订单创建失败（如库存冲突），更新用户状态为“失败”
            redisTemplate.opsForValue().set(
                    "seckill:user:queue:" + userId + ":" + goodsId,
                    "failed",
                    600,
                    TimeUnit.SECONDS
            );
        }

    }
}